package com.digigames;

import java.util.ArrayList;
import java.util.List;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ListView;

public class ItemListActivity extends ListActivity {

	static final  String XMLURL = "http://digigames.com/data-xml.php";
	private ProgressDialog m_ProgressDialog = null;
	private ArrayList<ItemObject> m_items = null;
	private ItemObjectAdapter m_adapter;
	private Runnable theRunable;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.item_list);
		m_items = new ArrayList<ItemObject>();
		this.m_adapter = new ItemObjectAdapter(this, R.layout.item_row, m_items);
		setListAdapter(this.m_adapter);
		theRunable = new Runnable() {
			// @Override
			public void run() {
				getItems();
			}
		};

		Thread thread = new Thread(null, theRunable, "MagentoBackground");
		thread.start();
		
		m_ProgressDialog = ProgressDialog.show(ItemListActivity.this,
				"Please wait...", "Retrieving data ...", true);
	}
	
	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);	
		
		ItemObject item = m_items.get(position);
		Intent detailActivityIntent = new Intent(v.getContext(),
				ItemDetailActivity.class);	
		
		ItemDetailActivity.item = item.getItem();
		ItemDetailActivity.description = item.getDetail();		
		startActivityForResult(detailActivityIntent, 0);
	}

	private void getItems() {
		try {
			m_items = new ArrayList<ItemObject>();
			ParseXml();
			//Log.i("ARRAY", "" + m_items.size());
		} catch (Exception e) {
			Log.e("BACKGROUND_PROC", e.getMessage());
		}
		runOnUiThread(returnRes);
	}


	private void ParseXml() {	
		
		AndroidSaxFeedParser parser = new AndroidSaxFeedParser(XMLURL);		
		List<ItemObject> itemsList1 = new ArrayList<ItemObject>();
		itemsList1 = parser.parse();
		m_items = (ArrayList<ItemObject>) itemsList1;
	}

	private Runnable returnRes = new Runnable() {
		// @Override
		public void run() {
			if (m_items != null && m_items.size() > 0) {
				m_adapter.notifyDataSetChanged();
				for (int i = 0; i < m_items.size(); i++)
					m_adapter.add(m_items.get(i));
			} else {
				// lblNoBid.setText(getText(R.string.main_no_items));
			}
			m_ProgressDialog.dismiss();
			m_adapter.notifyDataSetChanged();
		}
	};
}
